package com.chen.base.utils;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.chen.root.annotation.DefaultValue;
import lombok.SneakyThrows;

import java.lang.reflect.Field;

/**
 * 必填项检查工具类
 * @author: ChenJinLong
 * @DATE: 2024/7/18
 **/
public class RequiredUtil {

    /**
     * 如果属性为null, 则设置默认
     * @param t 对象
     */
    @SneakyThrows
    public static <T> void setDefault(T t){
        for (Field field : t.getClass().getDeclaredFields()) {
            DefaultValue annotation = field.getAnnotation(DefaultValue.class);
            if (annotation != null){
                field.setAccessible(true);
                Object fieldValue = field.get(t);
                String defaultValue = annotation.value();

                if ((fieldValue == null || StrUtil.isBlankIfStr(fieldValue)) && StrUtil.isNotBlank(defaultValue)){
                    Class<?> type = field.getType();
                    if (type == String.class){
                        field.set(t, defaultValue);
                    }else if (type == Integer.class){
                        field.set(t, Integer.valueOf(defaultValue));
                    }else if (type == Boolean.class){
                        field.set(t, Boolean.valueOf(defaultValue));
                    }else if (type == Byte.class){
                        field.set(t, Byte.valueOf(defaultValue));
                    }else if (type == Double.class){
                        field.set(t, Double.valueOf(defaultValue));
                    }else if (type == Float.class){
                        field.set(t, Float.valueOf(defaultValue));
                    }else if (type == Long.class){
                        field.set(t, Long.valueOf(defaultValue));
                    }else if (type == Short.class){
                        field.set(t, Short.valueOf(defaultValue));
                    }
                }
            }
        }
    }

    /**
     * 校验属性
     * @param t 对象
     * @param isSetDefault 是否设置默认值
     */
    public static <T> void checkField(T t, Boolean isSetDefault){
        if (isSetDefault != null && isSetDefault){
            RequiredUtil.setDefault(t);
        }
        String validateStr = ValidateUtil.validate(t);
        Assert.isTrue(StrUtil.isBlank(validateStr), validateStr);
    }
}
